import libtcodpy as libtcod
import math
import textwrap
import shelve
import os.path
import random
import time
from datetime import datetime
 
#actual size of the window
SCREEN_WIDTH = 110
SCREEN_HEIGHT = 65
 
#size of the map
MAP_WIDTH = 85
MAP_HEIGHT = 40
 
#sizes and coordinates relevant for the GUI
INVENTORY_WIDTH = 75
CHARACTER_PANEL_WIDTH = SCREEN_WIDTH - MAP_WIDTH - 1
CHARACTER_PANEL_HEIGHT = SCREEN_HEIGHT
CHARACTER_PANEL_Y = 0
MAP_X = CHARACTER_PANEL_WIDTH
MAP_Y = 0
LOOK_PANEL_WIDTH = MAP_WIDTH
LOOK_PANEL_HEIGHT = 3
LOOK_PANEL_X = CHARACTER_PANEL_WIDTH + 1
LOOK_PANEL_Y = MAP_HEIGHT
BAR_WIDTH = CHARACTER_PANEL_WIDTH - 2
BAR_X = 1
MSG_X = CHARACTER_PANEL_WIDTH
MSG_Y = MAP_HEIGHT + LOOK_PANEL_HEIGHT
MSG_WIDTH = SCREEN_WIDTH - CHARACTER_PANEL_WIDTH - 1
MSG_HEIGHT = SCREEN_HEIGHT - MAP_HEIGHT - LOOK_PANEL_HEIGHT - 1
 
 
#create the list of game messages and their colors, starts empty
game_msgs = []
 
 
#parameters for dungeon generator
ROOM_MAX_SIZE = 25
ROOM_MIN_SIZE = 6
MAX_ROOMS = 45
MAX_ROOM_MONSTERS = 3
MAX_ROOM_ITEMS = 2
BUILDING_MAX_SIZE = 30
BUILDING_MIN_SIZE = 8
MAX_BUILDINGS = 9
 
 
FOV_ALGO = 0  #default FOV algorithm
FOV_LIGHT_WALLS = True  #light walls or not
TORCH_RADIUS = 10 
LIMIT_FPS = 20  #20 frames-per-second maximum
PLAYER_SPEED = 1 #number of frames to wait after moving/attacking
DEFAULT_SPEED = 10
DEFAULT_ATTACK_SPEED = 20
PLAYER_TOWN_HP_REFRESH_RATE = 0.01 # The amount of HP that refreshes every second in town

# Player starting statistics (starting at level 0)
PLAYER_START_HP = 5
PLAYER_START_STRENGTH = 10
PLAYER_START_DEFENSE = 10
PLAYER_START_DEXTERITY = 10
PLAYER_START_INTELLIGENCE = 10
PLAYER_START_MANA = 1
PLAYER_START_MANA_REFRESH_RATE = 0.10 # The amount of mana that refreshes every second

 
 
timeOfLastPlayerManaRefresh = None
timeOfLastPlayerHpRefresh = None
 
 
# Spell constants
FIREBALL_RADIUS = 3
FIREBALL_DAMAGE = 12
HEAL_AMOUNT = 5
LIGHTNING_DAMAGE = 20
LIGHTNING_RANGE = 5
CONFUSE_NUM_TURNS = 10
CONFUSE_RANGE = 6
 
 
#experience and level-ups
LEVEL_UP_BASE = 100
LEVEL_UP_FACTOR = 150
LEVEL_SCREEN_WIDTH = 50
CHARACTER_SCREEN_WIDTH = 40
 
color_dark_wall = libtcod.Color(100, 100, 110)
color_light_wall = libtcod.Color(150, 150, 150)
color_dark_ground = libtcod.Color(40, 30, 30)
color_light_ground = libtcod.Color(90, 75, 65)
 
color_dark_town_wall = libtcod.darkest_flame
color_light_town_wall = libtcod.darkest_flame
color_dark_town_exterior_ground1 = libtcod.darkest_green
color_dark_town_exterior_ground2 = libtcod.darkest_chartreuse
color_dark_town_exterior_ground3 = libtcod.darkest_sea
color_light_town_exterior_ground = libtcod.darkest_chartreuse
color_dark_town_interior_ground = libtcod.dark_gray
color_light_town_interior_ground = libtcod.gray
 
# Monster chances
monster_chances_1 = {'rat': 35, 'spider': 25, 'bat': 15, 'kobold': 15, 'goblin': 10}
monster_chances_3 = {'rat': 30, 'spider': 15, 'bat': 5, 'kobold': 25, 'goblin': 25}
monster_chances_5 = {'rat': 15, 'spider': 5, 'kobold': 30, 'goblin': 30, 'orc': 15, 'skeleton': 5}
monster_chances_7 = {'kobold': 15, 'goblin': 25, 'orc': 30, 'skeleton': 20, 'troll': 10}
monster_chances_9 = {'goblin': 10, 'orc': 20, 'skeleton': 20, 'troll': 35, 'gelatinous-cube': 15}
monster_chances_11 = {'troll': 30, 'drow': 30, 'gelatinous-cube': 20, 'wyrmling': 20}
monster_chances_13 = {'troll': 15, 'gelatinous-cube': 25, 'wyrmling': 45, 'dragon-young': 15}
monster_chances_15 = {'troll': 5, 'gelatinous-cube': 10, 'wyrmling': 35, 'dragon-young': 35, 'dragon-adult': 15}
monster_chances_17 = {'wyrmling': 15, 'dragon-young': 35, 'dragon-adult': 35, 'dragon-wyrm': 15}
monster_chances_19 = {'dragon-young': 15, 'dragon-adult': 35, 'dragon-wyrm': 35, 'dragon-ancient': 15}
monster_chances_21 = {'demon': 60, 'devil': 40}
 
 
# Material chances
material_chances_1 = {'wood': 60, 'bronze': 30, 'iron': 10, 'steel': 0, 'crystal': 0, 'mithril': 0, 'adamantine': 0}
material_chances_5 = {'wood': 30, 'bronze': 30, 'iron': 30, 'steel': 10, 'crystal': 0, 'mithril': 0, 'adamantine': 0}
material_chances_10 = {'wood': 10, 'bronze': 30, 'iron': 30, 'steel': 30, 'crystal': 0, 'mithril': 0, 'adamantine': 0}
material_chances_15 = {'wood': 0, 'bronze': 10, 'iron': 15, 'steel': 30, 'crystal': 30, 'mithril': 15, 'adamantine': 0}
material_chances_20 = {'wood': 0, 'bronze': 0, 'iron': 15, 'steel': 30, 'crystal': 30, 'mithril': 15, 'adamantine': 10}
 
 
# Instructions
INSTRUCTIONS = ["Move around with the arrow keys or numpad.", "Move into an enemy to melee attack.", "r performs ranged attack.", "a opens the ammo menu", "i opens Inventory.", "g gets items.", "d drops items.", "c shows the Character info.", "< goes up stairs", "> goes down stairs"]
 
# Represents a tile of the map
class Tile:
    def __init__(self, blocked, block_sight = None):
        self.blocked = blocked
 
        #all tiles start unexplored
        self.explored = False
 
        #by default, if a tile is blocked, it also blocks sight
        if block_sight is None: block_sight = blocked
        self.block_sight = block_sight
 
 
# A simple rectangle object, used to characterize a room on the map
class Rect:
    def __init__(self, x, y, w, h):
        self.x1 = x
        self.y1 = y
        self.x2 = x + w
        self.y2 = y + h
 
    def center(self):
        center_x = (self.x1 + self.x2) / 2
        center_y = (self.y1 + self.y2) / 2
        return (center_x, center_y)
 
    def intersect(self, other):
        #returns True if this rectangle intersects with another one
        return (self.x1 <= other.x2 and self.x2 >= other.x1 and
                self.y1 <= other.y2 and self.y2 >= other.y1)
 
 
 
# A component class containing combat-related properties and functions
class Combatant:
	def __init__(self, hp=1, defense=1, strength=1, dexterity=1, intelligence=1, mana=0, mana_refresh_rate=0.10, hp_refresh_rate=0, attack_speed=DEFAULT_ATTACK_SPEED, xp=0, death_function=None, skill_component=None):
		self.death_function = death_function
		self.base_max_hp = hp
		self.base_defense = defense
		self.base_strength = strength
		self.base_dexterity = dexterity
		self.base_intelligence = intelligence
		self.base_max_mana = mana
		self.base_mana_refresh_rate = mana_refresh_rate
		self.base_hp_refresh_rate = hp_refresh_rate
		self.attack_speed = attack_speed
		self.xp = xp
		self.hp = self.base_max_hp
		self.mana = self.base_max_mana
		if(skill_component is not None):
			self.skill = skill_component
			self.skill.owner = self
		else: self.skill = None
	
	@property
	def strength(self):  #return actual strength, by summing up the bonuses from all equipped items
		bonus = sum(equipment.strength_bonus for equipment in get_all_equipped(self.owner))
		return self.base_strength + bonus
	
	@property
	def dexterity(self):  #return actual dexterity, by summing up the bonuses from all equipped items
		bonus = sum(equipment.dexterity_bonus for equipment in get_all_equipped(self.owner))
		return self.base_dexterity + bonus
	
	@property
	def intelligence(self):  #return actual intelligence, by summing up the bonuses from all equipped items
		bonus = sum(equipment.intelligence_bonus for equipment in get_all_equipped(self.owner))
		return self.base_intelligence + bonus
	
	@property
	def defense(self):  #return actual defense, by summing up the bonuses from all equipped items
		bonus = sum(equipment.defense_bonus for equipment in get_all_equipped(self.owner))
		bonus += int(round(self.dexterity/4, 0)) # Every 4 points in dexterity increases defense
		if(self.skill is not None):
			bonus += self.skill.defense
		return self.base_defense + bonus
	
	@property
	def max_hp(self):  #return actual max_hp, by summing up the bonuses from all equipped items
		bonus = sum(equipment.max_hp_bonus for equipment in get_all_equipped(self.owner))
		bonus += int(round(self.strength/4, 0)) # Every 4 points in strength increases HP
		return self.base_max_hp + bonus
	
	@property
	def max_mana(self):  #return actual max_mana, by summing up the bonuses from all equipped items
		bonus = sum(equipment.max_mana_bonus for equipment in get_all_equipped(self.owner))
		bonus += int(round(self.intelligence/4, 0)) # Every 4 points in intelligence increases mana
		return self.base_max_mana + bonus
	
	@property # The amount of mana that refreshes every second
	def mana_refresh_rate(self):  #return mana refresh rate, by summing up the bonuses from all equipped items
		bonus = sum(equipment.mana_refresh_bonus for equipment in get_all_equipped(self.owner))
		bonus += int(round(self.intelligence/4, 0)) # Every 4 points in intelligence increases mana refresh rate
		return self.base_mana_refresh_rate + bonus
	
	@property # The aount of HP that refreshes every second (in town)
	def hp_refresh_rate(self):
		if(dungeon_level == 0):
			bonus = 0
			if(self.skill is not None):
				bonus += self.skill.survival
			return self.base_hp_refresh_rate + bonus
		else: return 0 # HP will ony refresh while resting in town
	
	@property
	def melee_combat_score(self):  #return the melee combat score
		bonus = sum(equipment.melee_combat_bonus for equipment in get_all_equipped(self.owner))
		if(self.skill is not None):
			bonus += self.skill.melee
		return self.strength + bonus
	
	@property
	def ranged_combat_score(self):  #return the ranged combat score
		bonus = sum(equipment.ranged_combat_bonus for equipment in get_all_equipped(self.owner))
		if(self.skill is not None):
			bonus += self.skill.ranged
		return self.base_max_mana + bonus
	
	@property
	def melee_combat_damage(self): # Get the base damage dealt with any equipped melee weapons
		bonus = sum(equipment.damage_bonus for equipment in get_all_equipped(self.owner))
		return (self.strength/4) + bonus
	
	@property
	def ranged_combat_damage(self): # Get the base damage dealt with any equipped melee weapons
		bonus = sum(equipment.damage_bonus for equipment in get_all_equipped(self.owner))
		return (self.dexterity/4) + bonus
	
	def take_damage(self, damage):
		#apply damage if possible
		if damage > 0:
			self.hp -= damage
		#check for death. if there's a death function, call it
		if self.hp <= 0:
			function = self.death_function
			if function is not None:
				function(self.owner)
			if self.owner != player:  #yield experience to the player
				player.combatant.xp += self.xp
		
	def heal(self, amount):
		#heal by the given amount, without going over the maximum
		self.hp += amount
		if self.hp > self.max_hp:
			self.hp = self.max_hp
	
	def attack(self, target, melee=True, damage_bonus=0):
		toHit = 0
		damage = 0
		d20 = d(20)
		success = False # Whether or not this attack succeeds
		# Melee
		if(melee): # Melee combat
			toHit = self.melee_combat_score + d20
			damage = self.melee_combat_damage + d(6) + damage_bonus
		else: # Ranged combat
			toHit = self.ranged_combat_score + d20
			damage = self.ranged_combat_damage + d(6) + damage_bonus
	
		if(d20 >= 20): # Check for critical hit
			msg = self.owner.name.capitalize() + ' scores a CRITICAL HIT! '
			if(self.owner == player):
					message(msg, libtcod.yellow)
			else:
				message(msg, libtcod.red)
			damage = damage * 2
	
		if(toHit > target.combatant.defense or d20 >= 20): # Hit!
			if damage > 0:
				msg = self.owner.name.capitalize() + ' hits ' + target.name + ' (' + str(damage) + ' damage)'
				if(self.owner == player):
					message(msg, libtcod.light_yellow)
					if(player.combatant.skill is not None):
						if(melee):
							player.combatant.skill.melee += 0.01
						else:
							player.combatant.skill.ranged += 0.01
				else:
					message(msg, libtcod.light_red)
				target.combatant.take_damage(damage)
			else: # No damage dealt
				msg = self.owner.name.capitalize() + ' hits ' + target.name + ' but it has no effect!'
				message(msg, libtcod.light_gray)
			success = True
		else: # Miss !
			msg = self.owner.name.capitalize() + ' misses ' + target.name
			if(self.owner == player):
				message(msg, libtcod.light_gray)
			else:
				message(msg, libtcod.lighter_gray)
				if(player.combatant.skill is not None):
					player.combatant.skill.defense += 0.01
			success = False
		
		self.owner.wait = self.attack_speed
		return success # Whether or not this attack succeeds
	
 
 
# AI component class for a basic monster
class BasicMonster:
    def take_turn(self):
        #a basic monster takes its turn. If you can see it, it can see you
        monster = self.owner
        if libtcod.map_is_in_fov(fov_map, monster.x, monster.y):
            #move towards player if far away
            if monster.distance_to(player) >= 2:
                monster.move_towards(player.x, player.y)
 
            #close enough, attack! (if the player is still alive.)
            elif player.combatant.hp > 0:
                monster.combatant.attack(player)
 
 
# AI component class for a temporarily confused monster (stumbles around)
class ConfusedMonster:
    def __init__(self, old_ai, num_turns=CONFUSE_NUM_TURNS):
        self.old_ai = old_ai
        self.num_turns = num_turns
 
    def take_turn(self):
        if self.num_turns > 0:  #still confused...
            #move in a random direction, and decrease the number of turns confused
            self.owner.move(libtcod.random_get_int(0, -1, 1), libtcod.random_get_int(0, -1, 1))
            self.num_turns -= 1
 
        else:  #restore the previous AI (this one will be deleted because it's not referenced anymore)
            self.owner.ai = self.old_ai
            message('The ' + self.owner.name + ' is no longer confused!', libtcod.red)
 
 
# A generic object that is meant to hold various components to further define its
# functionality and purpose.
# It's always represented by a character on screen.
class Object:
    def __init__(self, x, y, char, name, color, blocks=False, speed=DEFAULT_SPEED, always_visible=False, combatant=None, ai=None, item=None, equipment=None):
        self.x = x
        self.y = y
        self.char = char
        self.name = name
        self.color = color
        self.blocks = blocks
        self.always_visible = always_visible
        self.speed = speed
        self.wait = 0
        self.combatant = combatant
        if self.combatant:  #let the combatant component know who owns it
            self.combatant.owner = self
 
        self.ai = ai
        if self.ai:  #let the AI component know who owns it
            self.ai.owner = self
        
        self.item = item
        if self.item:  #let the Item component know who owns it
            self.item.owner = self
            self.item.name = name
 
        self.equipment = equipment
        if self.equipment:  #let the Equipment component know who owns it
            self.equipment.owner = self
            #there must be an Item component for the Equipment component to work properly
            self.item = Item(quantity=equipment.quantity)
            self.item.owner = self
 
    def move(self, dx, dy):
        #move by the given amount, if the destination is not blocked
        if not is_blocked(self.x + dx, self.y + dy):
            self.x += dx
            self.y += dy
            self.wait = self.speed
 
    def distance_to(self, other):
        #return the distance to another object
        dx = other.x - self.x
        dy = other.y - self.y
        return math.sqrt(dx ** 2 + dy ** 2)

    def distance(self, x, y):
        #return the distance to some coordinates
        return math.sqrt((x - self.x) ** 2 + (y - self.y) ** 2)
 
    def move_towards(self, target_x, target_y):
        #vector from this object to the target, and distance
        dx = target_x - self.x
        dy = target_y - self.y
        distance = math.sqrt(dx ** 2 + dy ** 2)
 
        #normalize it to length 1 (preserving direction), then round it and
        #convert to integer so the movement is restricted to the map grid
        dx = int(round(dx / distance))
        dy = int(round(dy / distance))
        self.move(dx, dy)
 
    # Instantly moves the object to the (x, y) location specified
    def place_at(self, x, y):
        self.clear()
        self.x = x
        self.y = y
        self.draw()
 
    def draw(self):
        #only show if it's visible to the player; or it's set to "always visible" and on an explored tile
        if (libtcod.map_is_in_fov(fov_map, self.x, self.y) or (self.always_visible and map[self.x][self.y].explored)):
            #set the color and then draw the character that represents this object at its position
            libtcod.console_set_default_foreground(con, self.color)
            libtcod.console_put_char(con, self.x, self.y, self.char, libtcod.BKGND_NONE)
 
    def clear(self):
        #erase the character that represents this object
        libtcod.console_put_char(con, self.x, self.y, ' ', libtcod.BKGND_NONE)
 
    def send_to_back(self):
        #make this object be drawn first, so all others appear above it if they're in the same tile.
        global objects
        objects.remove(self)
        objects.insert(0, self)
 
 
# A physical item that can be picked up and possibly used
class Item:
    def __init__(self, use_function=None, isMoney=False, quantity=1, value=0.00):
        self.use_function = use_function
        self.isMoney = isMoney
        self.quantity = quantity
        self.value = value
    
    def isItemAlreadyInInventory(self):
        name = self.owner.name
        for item in inventory:
            if(item.name == name): return True
        return False
    
    def getExistingItemInInventory(self):
        name = self.owner.name
        for item in inventory:
            if(item.name == name): return item
        return None
    
    def pick_up(self):
        #add to the player's inventory and remove from the map
        existing_item = self.getExistingItemInInventory() # Check to see if we already have this
        if len(inventory) >= 26 and not self.isMoney:
            message('Your inventory has no room for ' + self.owner.name + '.', libtcod.white)
        elif self.isMoney:
            player.money += self.value
            objects.remove(self.owner)
            message('You picked up ' + self.owner.name + ' worth ' + money_str(self.value) + ' gold!', libtcod.brass)
        elif(self.owner.equipment is not None and self.owner.equipment.slot == 'ammo'):
            add_ammo(self.owner.name, quantity=self.quantity, damage_bonus=self.owner.equipment.strength_bonus)
            objects.remove(self.owner)
            if(player.current_ammo is None): player.current_ammo = player.ammo[self.owner.name] # Auto-select ammo
        elif(existing_item is not None and existing_item.item): # Do we already have some of this item in inventory?
            existing_item.item.quantity += self.quantity
            objects.remove(self.owner)
            message('You picked up ' + str(self.quantity) + ' ' + self.owner.name + '.', libtcod.green)
        else:
            inventory.append(self.owner)
            objects.remove(self.owner)
            message('You picked up ' + str(self.quantity) + ' ' + self.owner.name + '.', libtcod.green)
            #special case: automatically equip, if the corresponding equipment slot is unused
            equipment = self.owner.equipment
            if equipment and get_equipped_in_slot(equipment.slot) is None:
                equipment.equip()
 
    def use(self):
        #special case: if the object has the Equipment component, the "use" action is to equip/dequip
        if self.owner.equipment:
            self.owner.equipment.toggle_equip()
            return
 
        #just call the "use_function" if it is defined
        if self.use_function is None:
            message('The ' + self.owner.name + ' cannot be used.')
        else:
            if self.use_function() != 'cancelled':
                self.quantity -= 1
                if(self.quantity == 0):
                    inventory.remove(self.owner)  #destroy after use, unless it was cancelled for some reason
    
    def drop(self):
        #add to the map and remove from the player's inventory. also, place it at the player's coordinates
        objects.append(self.owner)
        #special case: if the object has the Equipment component, dequip it before dropping
        if self.owner.equipment:
            self.owner.equipment.dequip()
        inventory.remove(self.owner)
        self.owner.x = player.x
        self.owner.y = player.y
        message('You dropped ' + str(self.quantity) + ' ' + self.owner.name + '.', libtcod.gray)
 
 
 
# An object that can be equipped, yielding bonuses.
# Automatically adds the Item component.
class Equipment:
    def __init__(self, slot, strength_bonus=0, defense_bonus=0, max_hp_bonus=0, max_mana_bonus=0, mana_refresh_bonus=0, dexterity_bonus=0, intelligence_bonus=0, damage_bonus=0, melee_combat_bonus=0, ranged_combat_bonus=0, range=0, quantity=1, material=None):
        self.material_bonus = self.get_material_bonus(material)
        self.strength_bonus = strength_bonus + self.material_bonus
        self.defense_bonus = defense_bonus + self.material_bonus
        self.dexterity_bonus = dexterity_bonus + self.material_bonus
        self.intelligence_bonus = intelligence_bonus + self.material_bonus
        self.damage_bonus = damage_bonus + self.material_bonus
        self.melee_combat_bonus = melee_combat_bonus + self.material_bonus
        self.ranged_combat_bonus = ranged_combat_bonus + self.material_bonus
        self.max_hp_bonus = max_hp_bonus
        self.max_mana_bonus = max_mana_bonus
        self.mana_refresh_bonus = mana_refresh_bonus
        self.range = range # Melee weapons don't have a range
        self.slot = slot
        self.quantity = quantity
        self.is_equipped = False
 
    def toggle_equip(self):  #toggle equip/dequip status
        if self.is_equipped:
            self.dequip()
        else:
            self.equip()
 
    def equip(self):
        #if the slot is already being used, dequip whatever is there first
        old_equipment = get_equipped_in_slot(self.slot)
        if old_equipment is not None:
            old_equipment.dequip()
        #equip object and show a message about it
        self.is_equipped = True
        message('Equipped ' + self.owner.name + ' on ' + self.slot + '.', libtcod.light_green)
 
    def dequip(self):
        #dequip object and show a message about it
        if not self.is_equipped: return
        self.is_equipped = False
        message('Unequipped ' + self.owner.name + ' from ' + self.slot + '.', libtcod.dark_green)
    
    def getOwner(self):
        return self.owner
 
    def get_material_bonus(self, material):
        # Get any bonuses from the material
        if (material is None):
            return 0
        elif (material == 'wood'):
            return 0.25
        elif (material == 'bronze'):
            return 1
        elif (material == 'iron'):
            return 2
        elif (material == 'steel'):
            return 3
        elif (material == 'crystal'):
            return 4
        elif (material == 'mithril'):
            return 6
        elif (material == 'adamantine'):
            return 8
        else:
            return 0
 
 
# Skill component class for the Combatant component class
class Skill:
	def __init__(self):
		#Combat Skills
		self.melee_skill = 0# Increases melee combat score
		self.ranged_skill = 0 # Increases ranged combat score
		self.defense_skill = 0# Increases defense score
		#Utility Skills
		self.survival_skill = 0 # Increases hp refresh rate
		self.magic_skill = 0# Increases mana refresh rate
		self.dungeoneering_skill = 0# Increases quantity of treasure found
	
	@property
	def melee(self):
		return self.melee_skill
	
	@property
	def ranged(self):
		return self.ranged_skill
	
	@property
	def defense(self):
		return self.defense_skill
	
	@property
	def survival(self):
		return self.survival_skill
	
	@property
	def magic(self):
		return self.magic_skill
	
	@property
	def dungeoneering(self):
		return self.dungeoneering_skill
 
 
# Simple data structure to hold ammunition information
class Ammo:
	def __init__(self, name, quantity=1, damage_bonus=1):
		self.name = name
		self.quantity = quantity
		self.damage_bonus = damage_bonus
 
##
## END OF CLASSES
##
 
 
# Standard dice rolling function
def d(sides):
	return random.randint(1, sides)
 
 
def add_ammo(name, quantity, damage_bonus):
	ammo = Ammo(name, quantity, damage_bonus)
	if name in player.ammo:
		player.ammo[name].quantity += quantity # Add to existing ammo
		message("Added " + str(quantity) + " " + name + " to existing ammunition.", libtcod.light_green)
	else:
		player.ammo[name] = ammo
		message("Added " + str(quantity) + " new " + name + " to ammunition.", libtcod.light_green)
 
 
def choose_ammo():
	ammo = ammo_menu()
	player.current_ammo = ammo
	if ammo is not None:
		message("Equipped " + ammo.name + " as ammunition.", libtcod.light_green)
	else:
		message("Unequipped ammunition.", libtcod.light_green)
 
 
# Used for formatting money to read as 1K, 2.5M, etc, to save space.
def money_str(value):
	if(value >= 1000.00 and value < 1000000.00):
		return str(value / 1000.00) + 'K'
	elif(value >= 1000000.00 and value < 1000000000.00):
		return str(value / 1000000.00) + 'M'
	elif(value >= 1000000000.00):
		return str(value / 1000000000.00) + 'B'
	else:
		return str(value)
 
 
# Returns the equipment in a slot, or None if it's empty
def get_equipped_in_slot(slot):
    for obj in inventory:
        if obj.equipment and obj.equipment.slot == slot and obj.equipment.is_equipped:
            return obj.equipment
    return None
 
 
# Returns a list of equipped items
def get_all_equipped(obj):
    if obj == player:
        equipped_list = []
        for item in inventory:
            if item.equipment and item.equipment.is_equipped:
                equipped_list.append(item.equipment)
        return equipped_list
    else:
        return []  #other objects have no equipment
 
 
# Returns a value that depends on level.
# The table specifies what value occurs after each level; default is 0
def from_dungeon_level(table):
    for (value, level) in reversed(table):
        if dungeon_level >= level:
            return value
    return 0
 
 
# Choose one option from a list of chances, returning its index
def random_choice_index(chances):
    #the dice will land on some number between 1 and the sum of the chances
    dice = libtcod.random_get_int(0, 1, sum(chances))
 
    #go through all chances, keeping the sum so far
    running_sum = 0
    choice = 0
    for chance in chances:
        running_sum += chance
 
        #see if the dice landed in the part that corresponds to this choice
        if dice <= running_sum:
            return choice
        choice += 1
 
 
# CHoose one option from dictionary of chances, returning its key
def random_choice(chances_dict):
    chances = chances_dict.values()
    strings = chances_dict.keys()
    return strings[random_choice_index(chances)]
 
 
# Find the closest enemy, up to a maximum range, and in the player's FOV
def closest_monster(max_range):
    closest_enemy = None
    closest_dist = max_range + 1  #start with (slightly more than) maximum range
 
    for object in objects:
        if object.combatant and not object == player and libtcod.map_is_in_fov(fov_map, object.x, object.y):
            #calculate distance between this object and the player
            dist = player.distance_to(object)
            if dist < closest_dist:  #it's closer, so remember it
                closest_enemy = object
                closest_dist = dist
    return closest_enemy
 
 
# Refresh the mana by the mana_refresh_rate if a second has passed
def refresh_player_mana_if_applicable():
	global timeOfLastPlayerManaRefresh
	if(timeOfLastPlayerManaRefresh is None): timeOfLastPlayerManaRefresh = time.time()
	if(player.combatant.mana >= player.combatant.max_mana): return
	elapsed = time.time() - timeOfLastPlayerManaRefresh
	if(elapsed >= 0.01): # Broken into hundreths for smooth refresh animation
		player.combatant.mana += round(player.combatant.mana_refresh_rate / 100, 2)
		if(player.combatant.mana > player.combatant.max_mana):
			player.combatant.mana = player.combatant.max_mana
		timeOfLastPlayerManaRefresh = time.time()
 
 
# Refresh the HP by the hp_refresh_rate if a second has passed in town
def refresh_player_hp_if_applicable():
	global timeOfLastPlayerHpRefresh
	if(timeOfLastPlayerHpRefresh is None): timeOfLastPlayerHpRefresh = time.time()
	if(dungeon_level != 0 or player.combatant.hp >= player.combatant.max_hp): return
	elapsed = time.time() - timeOfLastPlayerHpRefresh
	if(elapsed >= 1):
		player.combatant.hp += player.combatant.hp_refresh_rate
		if(player.combatant.hp > player.combatant.max_hp):
			player.combatant.hp = player.combatant.max_hp
		timeOfLastPlayerHpRefresh = time.time()
 
 
# Refresh the player stats that are able to do so
def refresh_applicable_player_stats():
	refresh_player_mana_if_applicable()
	refresh_player_hp_if_applicable()
 
 
# See if the player's experience is enough to level up
def check_level_up():
    level_up_xp = LEVEL_UP_BASE + player.level * LEVEL_UP_FACTOR
    if player.combatant.xp >= level_up_xp:
        #it is! level up
        player.level += 1
        player.combatant.xp -= level_up_xp
        message('Your skills grow stronger! YOU REACHED LEVEL ' + str(player.level) + '!', libtcod.sky)
        choice = None
        while choice == None:  #keep asking until a choice is made
            choice = menu('Level up! Choose a stat to raise:\n',
                ['Strength (+1 from ' + str(player.combatant.strength) + ')',
                'Dexterity (+1 from ' + str(player.combatant.dexterity) + ')',
                'Intelligence (+1 from ' + str(player.combatant.intelligence) + ')'], LEVEL_SCREEN_WIDTH, color=libtcod.light_yellow)
 
        # Certain stats increase automatically
        player.combatant.base_max_hp += 15 # Player gains 15 HP every level
        player.combatant.hp += 15
        player.combatant.base_max_mana += 2 * player.level # Player gains 2 x level mana points every level
        player.combatant.mana += 2 * player.level
 
        if choice == 0:
            player.combatant.base_strength += 1
        elif choice == 1:
            player.combatant.base_dexterity += 1
        elif choice == 2:
            player.combatant.base_intelligence += 1
 
 
##
## Spell Functions
##
 
# Heal the player
def cast_heal():
    #heal the player
    if player.combatant.hp == player.combatant.max_hp:
        message('You are already at full health.', libtcod.white)
        return 'cancelled'
 
    message('Your wounds start to feel better!', libtcod.light_violet)
    player.combatant.heal(player.level * HEAL_AMOUNT)
 
 
# Area-of-effect spell, centered on target
def cast_fireball():
    #ask the player for a target tile to throw a fireball at
    message('Left-click a target tile for the fireball, or right-click to cancel.', libtcod.light_cyan)
    (x, y) = target_tile()
    if x is None: return 'cancelled'
    message('The fireball explodes, burning everything within ' + str(FIREBALL_RADIUS) + ' tiles!', libtcod.light_blue)
 
    for obj in objects:  #damage every combatant in range, including the player
        if obj.distance(x, y) <= FIREBALL_RADIUS and obj.combatant:
            message('The ' + obj.name + ' gets burned for ' + str(FIREBALL_DAMAGE) + ' hit points.', libtcod.orange)
            obj.combatant.take_damage(FIREBALL_DAMAGE)
 
 
# Does a lot of damage to a target
def cast_lightning():
    #find closest enemy (inside a maximum range) and damage it
    monster = closest_monster(LIGHTNING_RANGE)
    if monster is None:  #no enemy found within maximum range
        message('No enemy is close enough to strike with Lightning Bolt.', libtcod.white)
        return 'cancelled'
 
    #zap it!
    message('A Lightning Bolt strikes the ' + monster.name + ' with loud thunder! ('
        + str(LIGHTNING_DAMAGE) + ' damage).', libtcod.light_blue)
    monster.combatant.take_damage(LIGHTNING_DAMAGE)
 
 
# Confuses a target
def cast_confuse():
    #ask the player for a target to confuse
    message('Left-click an enemy to confuse it, or right-click to cancel.', libtcod.light_cyan)
    monster = target_monster(CONFUSE_RANGE)
    if monster is None: return 'cancelled'
    #replace the monster's AI with a "confused" one; after some turns it will restore the old AI
    old_ai = monster.ai
    monster.ai = ConfusedMonster(old_ai)
    monster.ai.owner = monster  #tell the new component who owns it
    message('The eyes of the ' + monster.name + ' look vacant, as it starts to stumble around!', libtcod.light_blue)
 
##
## End of Spell Functions
##
 
 
# Check to see if a tile is blocked by anything
def is_blocked(x, y):
    #first test the map tile
    if map[x][y].blocked:
        return True
 
    #now check for any blocking objects
    for object in objects:
        if object.blocks and object.x == x and object.y == y:
            return True
 
    return False
 
 
# Defines what happens when the player dies
def player_death(player):
    #the game ended!
    global game_state
    message('You have died!', libtcod.red)
    game_state = 'dead'
 
    #for added effect, transform the player into a corpse!
    player.char = 'x'
    player.color = libtcod.dark_red
 
 
# Defines what happens when a monster dies
def monster_death(monster):
    #transform it into a nasty corpse! it doesn't block, can't be
    #attacked and doesn't move
    message('The ' + monster.name + ' is dead! (+' + str(monster.combatant.xp) + ' xp)', libtcod.purple)
    monster.char = 'x'
    monster.color = libtcod.darkest_flame
    monster.blocks = False
    monster.combatant = None
    monster.ai = None
    monster.name = monster.name + ' remains'
    monster.always_visible = True
    monster.send_to_back()
 
 
 
##
## Map creation functions
##
 
# Creates a room out of a rectangle of tiles
def create_room(room):
    global map
    for x in range(room.x1 + 1, room.x2):
        for y in range(room.y1 + 1, room.y2):
            map[x][y].blocked = False
            map[x][y].block_sight = False
 
 
# Creates a building out of a rectangle of tiles
# Intended to be further carved out by create_room()
def create_building(room):
    global map
    for x in range(room.x1 + 1, room.x2):
        for y in range(room.y1 + 1, room.y2):
            map[x][y].blocked = True
            map[x][y].block_sight = True
 
 
# Creates a horizontal tunnel from x1 to x2
def create_h_tunnel(x1, x2, y):
    global map
    #horizontal tunnel. min() and max() are used in case x1>x2
    for x in range(min(x1, x2), max(x1, x2) + 1):
        map[x][y].blocked = False
        map[x][y].block_sight = False
 
 
# Creates a vertical tunnel from y1 to y2
def create_v_tunnel(y1, y2, x):
    global map
    #vertical tunnel
    for y in range(min(y1, y2), max(y1, y2) + 1):
        map[x][y].blocked = False
        map[x][y].block_sight = False
 
 
# Creates the entire map
# Can specify if we are making the map because we are coming from one level down, or from one level up
def make_map(from_down=False, from_up=True):
    global map, objects, downStairs, upStairs
    
    # The list of objects with just the player
    objects = [player]
 
    #fill map with "blocked" tiles
    map = [[ Tile(True)
        for y in range(MAP_HEIGHT) ]
            for x in range(MAP_WIDTH) ]
 
    rooms = []
    num_rooms = 0
 
    for r in range(MAX_ROOMS):
        #random width and height
        w = libtcod.random_get_int(0, ROOM_MIN_SIZE, ROOM_MAX_SIZE)
        h = libtcod.random_get_int(0, ROOM_MIN_SIZE, ROOM_MAX_SIZE)
        #random position without going out of the boundaries of the map
        x = libtcod.random_get_int(0, 0, MAP_WIDTH - w - 1)
        y = libtcod.random_get_int(0, 0, MAP_HEIGHT - h - 1)
 
        #"Rect" class makes rectangles easier to work with
        new_room = Rect(x, y, w, h)
 
        #run through the other rooms and see if they intersect with this one
        failed = False
        for other_room in rooms:
            if new_room.intersect(other_room):
                failed = True
                break
 
        if not failed:
            #this means there are no intersections, so this room is valid
 
            #"paint" it to the map's tiles
            create_room(new_room)
 
            #add some contents to this room, such as monsters
            place_objects(new_room)
 
            #center coordinates of new room, will be useful later
            (new_x, new_y) = new_room.center()
 
            if num_rooms == 0:
                #this is the first room, where the player starts at
                player.x = new_x
                player.y = new_y
                
                ### Place any debug items ###
                #debug_mat = 'bronze'
                #debug_equipment_component = Equipment(slot='ammo', strength_bonus=1, quantity=10, material=debug_mat)
                #debug_item = Object(new_x + 1, new_y + 1, '#', debug_mat + ' arrows', libtcod.orange, equipment=debug_equipment_component)
                #objects.append(debug_item)
                
                #debug_mat2 = 'wood'
                #debug_equipment_component2 = Equipment(slot='main hand', strength_bonus=1, range=7, material=debug_mat)
                #debug_item2 = Object(new_x - 1, new_y - 1, '}', debug_mat2 + ' bow', libtcod.orange, equipment=debug_equipment_component2)
                #objects.append(debug_item2)
                #############################
                
                # Also place the appropriate stairs here
                if(from_up): # We just went down a level, which means these stairs go back up
                    upStairs = Object(new_x, new_y, '<', 'stairs up', libtcod.white, always_visible=True)
                    objects.append(upStairs)
                else: # We just went up a level, which means these stairs go back down
                    downStairs = Object(new_x, new_y, '>', 'stairs down', libtcod.white, always_visible=True)
                    objects.append(downStairs)
            else:
                #all rooms after the first:
                #connect it to the previous room with a tunnel
 
                #center coordinates of previous room
                (prev_x, prev_y) = rooms[num_rooms-1].center()
 
                #draw a coin (random number that is either 0 or 1)
                if libtcod.random_get_int(0, 0, 1) == 1:
                    #first move horizontally, then vertically
                    create_h_tunnel(prev_x, new_x, prev_y)
                    create_v_tunnel(prev_y, new_y, new_x)
                else:
                    #first move vertically, then horizontally
                    create_v_tunnel(prev_y, new_y, prev_x)
                    create_h_tunnel(prev_x, new_x, new_y)
 
            #finally, append the new room to the list
            rooms.append(new_room)
            num_rooms += 1
 
    #create appropriate stairs at the center of the last room
    if(from_up): # We already placed up stairs in the map, we need to place down stairs
        downStairs = Object(new_x, new_y, '>', 'stairs down', libtcod.white, always_visible=True)
        objects.append(downStairs)
    else: # We already placed down stairs in the map, we need to place up stairs
        upStairs = Object(new_x, new_y, '<', 'stairs up', libtcod.white, always_visible=True)
        objects.append(upStairs)
 
 
# Creates a town map
# Can specify if we are making the map because we are coming from one level down, or from one level up
def make_town_map(from_down=True, from_up=False):
    global map, objects, downStairs, upStairs
    
    # The list of objects with just the player
    objects = [player]
 
    #fill map with "open" tiles
    map = [[ Tile(False)
        for y in range(MAP_HEIGHT) ]
            for x in range(MAP_WIDTH) ]
 
    rooms = []
    num_rooms = 0
 
    for r in range(MAX_ROOMS):
        #random width and height
        w = libtcod.random_get_int(0, ROOM_MIN_SIZE, ROOM_MAX_SIZE)
        h = libtcod.random_get_int(0, ROOM_MIN_SIZE, ROOM_MAX_SIZE)
        #random position without going out of the boundaries of the map
        x = libtcod.random_get_int(0, 0, MAP_WIDTH - w - 1)
        y = libtcod.random_get_int(0, 0, MAP_HEIGHT - h - 1)
 
        #"Rect" class makes rectangles easier to work with
        new_room = Rect(x, y, w, h)
        new_room_border = Rect(x-1, y-1, w+2, h+2)
 
        #run through the other rooms and see if they intersect with this one
        failed = False
        for other_room in rooms:
            if new_room_border.intersect(other_room):
                failed = True
                break
 
        if not failed:
            #this means there are no intersections, so this room is valid
 
            #"paint" it to the map's tiles
            create_building(new_room_border)
            create_room(new_room)
 
            #add some contents to this room, such as monsters
            #place_objects(new_room)
 
            #center coordinates of new room, will be useful later
            (new_x, new_y) = new_room.center()
 
            if num_rooms == 0:
                #this is the first room, where the player starts at
                player.x = new_x
                player.y = new_y
                
                ### Place any debug items ###
                #debug_mat = 'bronze'
                #debug_equipment_component = Equipment(slot='ammo', strength_bonus=1, quantity=10, material=debug_mat)
                #debug_item = Object(new_x + 1, new_y + 1, '#', debug_mat + ' arrows', libtcod.orange, equipment=debug_equipment_component)
                #objects.append(debug_item)
                
                #debug_mat2 = 'wood'
                #debug_equipment_component2 = Equipment(slot='main hand', strength_bonus=1, range=7, material=debug_mat)
                #debug_item2 = Object(new_x - 1, new_y - 1, '}', debug_mat2 + ' bow', libtcod.orange, equipment=debug_equipment_component2)
                #objects.append(debug_item2)
                #############################
                
                # Also place the appropriate stairs here
                if(from_up): # We just went down a level, which means these stairs go back up
                    upStairs = Object(new_x, new_y, '<', 'stairs up', libtcod.white, always_visible=True)
                    objects.append(upStairs)
                else: # We just went up a level, which means these stairs go back down
                    downStairs = Object(new_x+1, new_y, '>', 'stairs down', libtcod.white, always_visible=True)
                    objects.append(downStairs)
            else:
                #all rooms after the first:
                #connect it to the previous room with a "tunnel" to ensure all buildings have openings
 
                #center coordinates of previous room
                (prev_x, prev_y) = rooms[num_rooms-1].center()
 
                #draw a coin (random number that is either 0 or 1)
                if libtcod.random_get_int(0, 0, 1) == 1:
                    #first move horizontally, then vertically
                    create_h_tunnel(prev_x, new_x, prev_y)
                    create_v_tunnel(prev_y, new_y, new_x)
                else:
                    #first move vertically, then horizontally
                    create_v_tunnel(prev_y, new_y, prev_x)
                    create_h_tunnel(prev_x, new_x, new_y)
 
            #finally, append the new room to the list
            rooms.append(new_room)
            num_rooms += 1
 
    #create appropriate stairs at the center of the last room
    if(from_up): # We already placed up stairs in the map, we need to place down stairs
        downStairs = Object(new_x, new_y, '>', 'stairs down', libtcod.white, always_visible=True)
        objects.append(downStairs)
 
 
# Places all kinds of objects and creatures in the map
def place_objects(room):
	place_monsters(room)
	place_items(room)
 
 
# Gets the chance dictionary for monsters based on the dungeon level provided
def get_monster_chances(lvl):
	if lvl == 1:
		return monster_chances_1
	elif lvl > 1 and lvl <= 3:
		return monster_chances_3
	elif lvl > 3 and lvl <= 5:
		return monster_chances_5
	elif lvl > 5 and lvl <= 7:
		return monster_chances_7
	elif lvl > 7 and lvl <= 9:
		return monster_chances_9
	elif lvl > 9 and lvl <= 11:
		return monster_chances_11
	elif lvl > 11 and lvl <= 13:
		return monster_chances_13
	elif lvl > 13 and lvl <= 15:
		return monster_chances_15
	elif lvl > 15 and lvl <= 17:
		return monster_chances_17
	elif lvl > 17 and lvl <= 19:
		return monster_chances_19
	elif lvl > 19 and lvl <= 21:
		return monster_chances_21
	else:
		return monster_chances_1
 
 
# Gets the chance dictionary for materials based on the dungeon level provided
def get_material_chances(lvl):
	if lvl == 1:
		return material_chances_1
	elif lvl > 1 and lvl <= 5:
		return material_chances_5
	elif lvl > 5 and lvl <= 10:
		return material_chances_10
	elif lvl > 10 and lvl <= 15:
		return material_chances_15
	elif lvl > 15 and lvl <= 20:
		return material_chances_20
	elif lvl > 20:
		return material_chances_20
	else:
		return material_chances_5

 
 
# Places monsters in the map
def place_monsters(room):
	#choose random number of monsters
	num_monsters = libtcod.random_get_int(0, 0, MAX_ROOM_MONSTERS)
 
	for i in range(num_monsters):
		#choose random spot for this monster
		x = libtcod.random_get_int(0, room.x1+1, room.x2-1)
		y = libtcod.random_get_int(0, room.y1+1, room.y2-1)
 
		#only place it if the tile is not blocked
		if not is_blocked(x, y):
			monster_chances = get_monster_chances(dungeon_level)
			choice = random_choice(monster_chances)
			if choice == 'rat':
				combat_component = Combatant(hp=2, defense=0, strength=1, death_function=monster_death, xp=10)
				ai_component = BasicMonster()
				monster = Object(x, y, 'r', 'rat', libtcod.white, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'spider':
				combat_component = Combatant(hp=1, defense=0, strength=1, death_function=monster_death, xp=5)
				ai_component = BasicMonster()
				monster = Object(x, y, '*', 'spider', libtcod.black, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'bat':
				combat_component = Combatant(hp=1, defense=1, strength=1, death_function=monster_death, xp=7)
				ai_component = BasicMonster()
				monster = Object(x, y, 'b', 'bat', libtcod.black, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'orc':
				combat_component = Combatant(hp=10, defense=0, strength=3, death_function=monster_death, xp=35)
				ai_component = BasicMonster()
				monster = Object(x, y, 'o', 'orc', libtcod.desaturated_green, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'troll':
				combat_component = Combatant(hp=16, defense=1, strength=4, death_function=monster_death, xp=100)
				ai_component = BasicMonster()
				monster = Object(x, y, 'T', 'troll', libtcod.darker_green, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'goblin':
				combat_component = Combatant(hp=5, defense=0, strength=2, death_function=monster_death, xp=25)
				ai_component = BasicMonster()
				monster = Object(x, y, 'g', 'goblin', libtcod.Color(70, 130, 110), blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'kobold':
				combat_component = Combatant(hp=3, defense=0, strength=2, death_function=monster_death, xp=15)
				ai_component = BasicMonster()
				monster = Object(x, y, 'k', 'kobold', libtcod.Color(90, 165, 90), blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'skeleton':
				combat_component = Combatant(hp=5, defense=1, strength=3, death_function=monster_death, xp=25)
				ai_component = BasicMonster()
				monster = Object(x, y, 's', 'skeleton', libtcod.white, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'gelatinous-cube':
				combat_component = Combatant(hp=25, defense=3, strength=3, death_function=monster_death, xp=150)
				ai_component = BasicMonster()
				monster = Object(x, y, 'G', 'gelatinous cube', libtcod.green, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'drow':
				combat_component = Combatant(hp=16, defense=2, strength=3, death_function=monster_death, xp=115)
				ai_component = BasicMonster()
				monster = Object(x, y, 'd', 'drow', libtcod.black, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'wyrmling':
				combat_component = Combatant(hp=30, defense=6, strength=7, death_function=monster_death, xp=400)
				ai_component = BasicMonster()
				monster = Object(x, y, 'D', 'wyrmling', libtcod.lighter_red, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'dragon-young':
				combat_component = Combatant(hp=40, defense=8, strength=8, death_function=monster_death, xp=500)
				ai_component = BasicMonster()
				monster = Object(x, y, 'D', 'young dragon', libtcod.light_red, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'dragon-adult':
				combat_component = Combatant(hp=50, defense=9, strength=9, death_function=monster_death, xp=600)
				ai_component = BasicMonster()
				monster = Object(x, y, 'D', 'adult dragon', libtcod.red, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'dragon-wyrm':
				combat_component = Combatant(hp=60, defense=10, strength=10, death_function=monster_death, xp=750)
				ai_component = BasicMonster()
				monster = Object(x, y, 'D', 'dragon wyrm', libtcod.dark_red, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'dragon-ancient':
				combat_component = Combatant(hp=70, defense=12, strength=12, death_function=monster_death, xp=1000)
				ai_component = BasicMonster()
				monster = Object(x, y, 'D', 'dragon wyrm', libtcod.dark_red, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'demon':
				combat_component = Combatant(hp=30, defense=8, strength=12, death_function=monster_death, xp=850)
				ai_component = BasicMonster()
				monster = Object(x, y, 'X', 'demon', libtcod.dark_purple, blocks=True, combatant=combat_component, ai=ai_component)
			elif choice == 'devil':
				combat_component = Combatant(hp=50, defense=10, strength=15, death_function=monster_death, xp=1000)
				ai_component = BasicMonster()
				monster = Object(x, y, 'Z', 'Devil', libtcod.red, blocks=True, combatant=combat_component, ai=ai_component)
			else:
				combat_component = Combatant(hp=1, defense=0, strength=1, death_function=monster_death, xp=5)
				ai_component = BasicMonster()
				monster = Object(x, y, '*', 'spider', libtcod.black, blocks=True, combatant=combat_component, ai=ai_component)
			objects.append(monster)
 
 
# Places all kinds of items on the map
def place_items(room):
    #choose random number of items
    num_items = libtcod.random_get_int(0, 0, MAX_ROOM_ITEMS)
 
    for i in range(num_items):
        #choose random spot for this item
        x = libtcod.random_get_int(0, room.x1+1, room.x2-1)
        y = libtcod.random_get_int(0, room.y1+1, room.y2-1)
 
        #only place it if the tile is not blocked
        if not is_blocked(x, y):
            item_chances = {'potion': 25, 'scroll': 30, 'treasure': 45}
            choice = random_choice(item_chances)
            if choice == 'potion':
                item = get_random_potion(x, y)
            elif choice == 'scroll':
                item = get_random_scroll(x, y)
            elif choice == 'treasure':
                item = get_random_treasure(x, y)
            else:
                item = get_random_treasure(x, y)
 
            objects.append(item)
            item.send_to_back()  #items appear below other objects
 
 
# Gets a random type of potion
def get_random_potion(x, y):
	# Choose a random potion
	choice = libtcod.random_get_int(0, 1, 1)
	if choice == 1:
		item_component = Item(use_function=cast_heal) 
		item = Object(x, y, '!', 'healing potion', libtcod.light_violet, item=item_component, always_visible=True)
	else:
		item = ObjecT(x, y, '!', 'empty potion vial', libtcod.light_gray, always_visible=True)
	return item
 
 
# Gets a random type of scroll
def get_random_scroll(x, y):
	# Choose a random scroll
	choice = libtcod.random_get_int(0, 1, 3)
	if choice == 1:
		# Lightning Bolt
		item_component = Item(use_function=cast_lightning) 
		item = Object(x, y, '%', 'Scroll of Lightning Bolt', libtcod.brass, item=item_component, always_visible=True)
	elif choice == 2:
		# Confusion
		item_component = Item(use_function=cast_confuse) 
		item = Object(x, y, '%', 'Scroll of Confusion', libtcod.brass, item=item_component, always_visible=True)
	elif choice == 3:
		# Fireball
		item_component = Item(use_function=cast_fireball)
		item = Object(x, y, '%', 'Scroll of Fireball', libtcod.brass, item=item_component, always_visible=True)
	else: # Parchment
		item = Object(x, y, '%', 'parchment', libtcod.dark_brass, always_visible=True)
	return item
 
 
# Gets a random type of treasure
def get_random_treasure(x, y):
	# Choose a random piece of treasure
	choice = libtcod.random_get_int(0, 1, 10)
	amount = dungeon_level * d(8) + d(10)
	if(player.combatant.skill is not None): amount += player.combatant.skill.dungeoneering * d(4)
	if choice == 1:
		# Gold
		item_component = Item(isMoney=True, value=1.00 * amount)
		item = Object(x, y, '$', 'Gold', libtcod.gold, item=item_component, always_visible=True)
	elif choice == 2:
		# Silver
		item_component = Item(isMoney=True, value=0.10 * amount)
		item = Object(x, y, '$', 'Silver', libtcod.lighter_gray, item=item_component, always_visible=True)
	elif choice == 3:
		# Copper
		item_component = Item(isMoney=True, value=0.01 * amount)
		item = Object(x, y, '$', 'Copper', libtcod.orange, item=item_component, always_visible=True)
	elif choice == 4:
		# Ruby
		item_component = Item(isMoney=True, value=15.00 * amount)
		item = Object(x, y, '*', 'Ruby', libtcod.red, item=item_component, always_visible=True)
	elif choice == 5:
		# Emerald
		item_component = Item(isMoney=True, value=20.00 * amount)
		item = Object(x, y, '*', 'Emerald', libtcod.darker_green, item=item_component, always_visible=True)
	elif choice == 6:
		# Sapphire
		item_component = Item(isMoney=True, value=25.00 * amount)
		item = Object(x, y, '*', 'Sapphire', libtcod.blue, item=item_component, always_visible=True)
	else:
		item = get_random_equipment(x, y)
	return item
 
 
# Gets a random piece of equipment
def get_random_equipment(x, y):
	# Choose a random piece of equipment
	choice = libtcod.random_get_int(0, 1, 15)
	mat = get_random_material()
	if choice == 1: #Sword
		equipment_component = Equipment(slot='main hand', strength_bonus=2, material=mat)
		item = Object(x, y, '/', mat + ' sword', libtcod.light_gray, equipment=equipment_component)
	elif choice == 2: #Staff
		equipment_component = Equipment(slot='main hand', strength_bonus=1, material=mat)
		item = Object(x, y, '/', mat + ' staff', libtcod.dark_sepia, equipment=equipment_component)
	elif choice == 3: #Helm
		equipment_component = Equipment(slot='head', defense_bonus=1, material=mat)
		item = Object(x, y, 'u', mat + ' helm', libtcod.light_gray, equipment=equipment_component)
	elif choice == 4: #Shield
		equipment_component = Equipment(slot='off hand', defense_bonus=2, material=mat)
		item = Object(x, y, '[', mat + ' shield', libtcod.light_gray, equipment=equipment_component)
	elif choice == 5: #Axe
		equipment_component = Equipment(slot='main hand', strength_bonus=3, material=mat)
		item = Object(x, y, 'p', mat + ' axe', libtcod.light_gray, equipment=equipment_component)
	elif choice == 6: #Chain shirt
		equipment_component = Equipment(slot='torso', defense_bonus=3, material=mat)
		item = Object(x, y, 'M', mat + ' chain shirt', libtcod.lightest_blue, equipment=equipment_component)
	elif choice == 7: #Bow
		equipment_component = Equipment(slot='main hand', strength_bonus=0, range=5, material=mat)
		item = Object(x, y, "}", mat + ' bow', libtcod.sepia, equipment=equipment_component)
	elif choice == 8 or choice == 9 or choice == 10 or choice == 11: #Arrows
		equipment_component = Equipment(slot='ammo', strength_bonus=1.5, quantity=10, material=mat)
		item = Object(x, y, '#', mat + ' arrows', libtcod.dark_yellow, equipment=equipment_component)
	elif choice == 12: #Boots
		equipment_component = Equipment(slot='feet', defense_bonus=0, material=mat)
		item = Object(x, y, 'h', mat + ' boots', libtcod.black, equipment=equipment_component)
	elif choice == 15: #Ring of health
		equipment_component = Equipment(slot='left finger', max_hp_bonus=4)
		item = Object(x, y, ',', 'ring of health', libtcod.sky, equipment=equipment_component)
	else: # Stick
		equipment_component = Equipment(slot='main hand', strength_bonus=0, material='wood')
		item = Object(x, y, '~', 'stick', libtcod.sepia, equipment=equipment_component)
	
	return item
 
 
# Get a random material for a piece of equipment
def get_random_material():
	material_chances = get_material_chances(dungeon_level)
	material = random_choice(material_chances)
	return material
 
 
##
## End of map creation functions
##
 
 
def console_print_color(console, x, y, text, r, g, b):
	string = "%c%c%c%c" + text + "%c"
	libtcod.console_print(console, x, y, string%(libtcod.COLCTRL_FORE_RGB,r,g,b, libtcod.COLCTRL_STOP))
 
 
def console_print_color2(console, x, y, text, foreColor, backColor=libtcod.black):
	libtcod.console_set_color_control(libtcod.COLCTRL_1, foreColor, backColor)
	string = "%c" + text + "%c"
	libtcod.console_print(console, x, y, string%(libtcod.COLCTRL_1, libtcod.COLCTRL_STOP))
 
 
# The main rendering function used to draw the screen
def render_all():
    global fov_map, color_dark_wall, color_light_wall
    global color_dark_ground, color_light_ground
    global color_dark_town_wall, color_light_town_wall
    global color_dark_town_exterior_ground1, color_dark_town_exterior_ground2, color_dark_town_exterior_ground3
    global color_light_town_exterior_ground, color_dark_town_interior_ground, color_light_town_interior_ground
    global fov_recompute
 
    inTown = dungeon_level == 0 # Dungeon Level 0 represents the town setting
 
    if fov_recompute:
        #recompute FOV if needed (the player moved or something)
        fov_recompute = False
        libtcod.map_compute_fov(fov_map, player.x, player.y, TORCH_RADIUS, FOV_LIGHT_WALLS, FOV_ALGO)
 
        #go through all tiles, and set their background color according to the FOV
        for y in range(MAP_HEIGHT):
            for x in range(MAP_WIDTH):
                visible = libtcod.map_is_in_fov(fov_map, x, y)
                wall = map[x][y].block_sight
                if not visible: #if it's not visible right now, the player can only see it if it's explored
                    if inTown: # Consider all town tiles "explored"
                        if wall:
                            libtcod.console_set_char_background(con, x, y, color_dark_town_wall, libtcod.BKGND_SET)
                        else:
                            libtcod.console_set_char_background(con, x, y, color_dark_town_exterior_ground1, libtcod.BKGND_SET)
                    else: # in Dungeon
                        if map[x][y].explored:
                            if wall:
                                libtcod.console_set_char_background(con, x, y, color_dark_wall, libtcod.BKGND_SET)
                            else:
                                libtcod.console_set_char_background(con, x, y, color_dark_ground, libtcod.BKGND_SET)
                else: # Since it's visible, explore it
                    if inTown:
                        if wall:
                            libtcod.console_set_char_background(con, x, y, color_light_town_wall, libtcod.BKGND_SET )
                        else:
                            libtcod.console_set_char_background(con, x, y, color_light_town_exterior_ground, libtcod.BKGND_SET )
                    else: # in Dungeon
                        if wall:
                            libtcod.console_set_char_background(con, x, y, color_light_wall, libtcod.BKGND_SET )
                        else:
                            libtcod.console_set_char_background(con, x, y, color_light_ground, libtcod.BKGND_SET )
                        #since it's visible, explore it
                        map[x][y].explored = True
 
    #draw all objects in the list, except the player. we want it to
    #always appear over all other objects! so it's drawn later.
    for object in objects:
        if object != player:
            object.draw()
    player.draw()
    
    #blit the contents of "con" to the root console
    libtcod.console_blit(con, 0, 0, MAP_WIDTH, MAP_HEIGHT, 0, MAP_X, MAP_Y)
	
	#prepare to render the GUI panel
    libtcod.console_set_default_background(panel, libtcod.black)
    libtcod.console_clear(panel)
    libtcod.console_set_default_background(look_panel, libtcod.black)
    libtcod.console_clear(look_panel)
    libtcod.console_set_default_background(msg_panel, libtcod.black)
    libtcod.console_clear(msg_panel)
 
    #print the game messages, one line at a time
    y = 1
    for (line, color) in game_msgs:
        libtcod.console_set_default_foreground(msg_panel, color)
        libtcod.console_print_ex(msg_panel, 0, y, libtcod.BKGND_NONE, libtcod.LEFT, line)
        y += 1
 
    #show the player's stats
    # Health Bar
    render_bar(1, 1, BAR_WIDTH, 'HP', player.combatant.hp, player.combatant.max_hp,
        libtcod.Color(230, 10, 50), libtcod.Color(90, 10, 10))
    
    # Mana Bar
    render_bar(1, 2, BAR_WIDTH, 'Mana', player.combatant.mana, player.combatant.max_mana,
        libtcod.Color(10, 135, 100), libtcod.Color(5, 85, 50))
 
    # XP Bar and player level
    level_up_xp = LEVEL_UP_BASE + player.level * LEVEL_UP_FACTOR
    render_bar(1, 3, BAR_WIDTH, 'XP', player.combatant.xp, level_up_xp,
        libtcod.dark_purple, libtcod.darkest_purple) 
    console_print_color2(panel, 1, 5, "Player Level  " + str(player.level), libtcod.sky)
 
    # Dungeon Level
    if(dungeon_level == 0): console_print_color2(panel, 1, 6, "(IN TOWN) ", libtcod.dark_green)
    else: console_print_color2(panel, 1, 6, "Dungeon Level " + str(dungeon_level), libtcod.red)
 
    # Money
    console_print_color2(panel, 1, 7, "Money (GP)    " + money_str(player.money), libtcod.gold)
    
    ### Character Attributes ###
    console_print_color2(panel, 1,  9, "STR:            " + str(player.combatant.strength), libtcod.lighter_green)
    console_print_color2(panel, 1, 10, " Melee:         " + str(player.combatant.melee_combat_score), libtcod.lighter_green)
    console_print_color2(panel, 1, 11, " Health:        " + str(player.combatant.max_hp), libtcod.lighter_green)
    console_print_color2(panel, 1, 12, "DEX:            " + str(player.combatant.dexterity), libtcod.lighter_green)
    console_print_color2(panel, 1, 13, " Defense:       " + str(player.combatant.defense), libtcod.lighter_green)
    console_print_color2(panel, 1, 14, " Ranged:        " + str(player.combatant.ranged_combat_score), libtcod.lighter_green)
    console_print_color2(panel, 1, 15, "INT:            " + str(player.combatant.intelligence), libtcod.lighter_green)
    console_print_color2(panel, 1, 16, " Mana:          " + str(player.combatant.max_mana), libtcod.lighter_green)
    console_print_color2(panel, 1, 17, "  Refresh Rate: " + str(player.combatant.mana_refresh_rate), libtcod.lighter_green)
    
    # Display main hand:
    mainHandEq = get_equipped_in_slot('main hand')
    console_print_color2(panel, 1, 31, "MAIN HAND: ", libtcod.white)
    if(mainHandEq is not None and mainHandEq.owner is not None):
        mainHand = mainHandEq.owner.item
        console_print_color2(panel, 1, 32, mainHandEq.owner.name, libtcod.white)
    else:
        console_print_color2(panel, 1, 32, "(empty)", libtcod.gray)
    
    # Display off hand:
    offHandEq = get_equipped_in_slot('off hand')
    console_print_color2(panel, 1, 34, "OFF HAND: ", libtcod.white)
    if(offHandEq is not None and offHandEq.owner is not None):
        offHand = offHandEq.owner.item
        console_print_color2(panel, 1, 35, offHandEq.owner.name, libtcod.white)
    else:
        console_print_color2(panel, 1, 35, "(empty)", libtcod.gray)
    
    # Display armor:
    armorEq = get_equipped_in_slot('torso')
    console_print_color2(panel, 1, 37, "ARMOR: ", libtcod.white)
    if(armorEq is not None and armorEq.owner is not None):
        armor = armorEq.owner.item
        console_print_color2(panel, 1, 38, armorEq.owner.name, libtcod.white)
    else:
        console_print_color2(panel, 1, 38, "(none)", libtcod.gray)
    
    # Display ammunition
    ammoEquipped = get_equipped_in_slot('ammo') # Equipment components of ammo
    console_print_color2(panel, 1, 40, "AMMUNITION: ", libtcod.white)
    if(player.current_ammo is not None):
        console_print_color2(panel, 1, 41,player.current_ammo.name + ' x' + str(player.current_ammo.quantity), libtcod.white)
    else:
        console_print_color2(panel, 1, 41, "(none)", libtcod.gray)
 
    # Display names of objects visible
    libtcod.console_set_default_foreground(look_panel, libtcod.lightest_blue)
    #libtcod.console_print_ex(look_panel, 0, 0, libtcod.BKGND_NONE, libtcod.LEFT, get_mouse_coords())
    libtcod.console_print_ex(look_panel, 0, 1, libtcod.BKGND_NONE, libtcod.LEFT, get_names_under_mouse())
    #libtcod.console_print_ex(look_panel, 0, 2, libtcod.BKGND_NONE, libtcod.LEFT, get_player_coords())
 
    #blit the contents of "panel" to the root console
    libtcod.console_blit(panel, 0, 0, CHARACTER_PANEL_WIDTH, CHARACTER_PANEL_HEIGHT, 0, 0, CHARACTER_PANEL_Y)
 
    # Blit the contents of the look panel to the root console
    libtcod.console_blit(look_panel, 0, 0, LOOK_PANEL_WIDTH, LOOK_PANEL_HEIGHT, 0, LOOK_PANEL_X, LOOK_PANEL_Y)
 
    # Blit the contents of message panel to the root console
    libtcod.console_blit(msg_panel, 0, 0, MSG_WIDTH, MSG_HEIGHT, 0, MSG_X, MSG_Y)
 
 
# Handles player movement and melee attacks
def player_move_or_attack(dx, dy):
    global fov_recompute
 
    #the coordinates the player is moving to/attacking
    x = player.x + dx
    y = player.y + dy
 
    #try to find an attackable object there
    target = None
    for object in objects:
        if object.combatant and object.x == x and object.y == y:
            target = object
            break
 
    #attack if target found, move otherwise
    if target is not None:
        player.combatant.attack(target)
    else:
        player.move(dx, dy)
        fov_recompute = True
 
 
# Shoots at a target with a ranged weapon
def player_ranged_attack(ranged_weapon):
    # Make sure we have ammo first
    ammo = player.current_ammo
    if(ammo is not None):
        if(ranged_weapon.equipment and ranged_weapon.equipment.range > 0):
            #ask the player for a target to attack
            message('Left-click an enemy to fire at it, or right-click to cancel.', libtcod.light_cyan)
            monster = target_monster(ranged_weapon.equipment.range)
            if monster is None: return 'cancelled'
            success = player.combatant.attack(monster, melee=False, damage_bonus = ammo.damage_bonus)
            if(success): ammo.quantity -= 1
            if(ammo.quantity <= 0): # Let's get rid of this and pick a new one, if we can
                player.current_ammo = None
                del player.ammo[ammo.name]
                choose_ammo()
 
 
# Utility wrapper method for checking if a location is in the player's FOV
def isInFov(x, y):
	return libtcod.map_is_in_fov(fov_map, x, y)
 
 
# Returns the position of a tile clicked in the player's FOV or within a range.
# Returns (None, None) if right-clicked, to cancel
def target_tile(max_range=None):
    global key, mouse
    while True:
        #render the screen. this erases the inventory and shows the names of objects under the mouse.
        libtcod.console_flush()
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS|libtcod.EVENT_MOUSE,key,mouse)
        render_all()
 
        (x, y) = (mouse.cx - MAP_X, mouse.cy)
        
        if mouse.rbutton_pressed or key.vk == libtcod.KEY_ESCAPE:
            return (None, None)  #cancel if the player right-clicked or pressed Escape
 
        #accept the target if the player clicked in FOV, and in case a range is specified, if it's in that range
        if (mouse.lbutton_pressed and libtcod.map_is_in_fov(fov_map, x, y) and (max_range is None or player.distance(x, y) <= max_range)):
            return (x, y)
 
 
# Returns a clicked monster inside FOV up to a range, or None of right-clicked
def target_monster(max_range=None):
    #returns a clicked monster inside FOV up to a range, or None if right-clicked
    while True:
        (x, y) = target_tile(max_range)
        if x is None:  #player cancelled
            return None
 
        #return the first clicked monster, otherwise continue looping
        for obj in objects:
            if obj.x == x and obj.y == y and obj.combatant and obj != player:
                return obj
 
 
# Returns a string with the name of all objects under the mouse
def get_names_under_mouse():
	global mouse
	
	(x, y) = (mouse.cx - MAP_X, mouse.cy)
	
	#create a list with the names of all objects at the mouse's coordinates and in FOV
	names = [obj.name for obj in objects if obj.x == x and obj.y == y] # and isInFov(obj.x, obj.y)]
	names = ', '.join(names) # join the names, separated by commas
	names = "You see: " + names.capitalize()
	return names
 
 
# Returns a string with the name of all objects within the FOV
def get_names_in_fov():
	names = [obj.name for obj in objects if isInFov(obj.x, obj.y) and obj.name is not 'player']
	names = ', '.join(names) # join the names, separated by commas
	names = "You see: " + names.capitalize()
	return names
 
 
def get_mouse_coords():
	return "Mouse: (" + str(mouse.cx - MAP_X) + ", " + str(mouse.cy) + ")"
 
 
def get_player_coords():
	return "Player at: (" + str(player.x) + ", " + str(player.y) + ")"
 
 
##
## CONTROLS
##
 
# Defines the controls
def handle_keys():
    global key;
 
    if key.vk == libtcod.KEY_ENTER and key.lalt:
        #Alt+Enter: toggle fullscreen
        libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
 
    elif key.vk == libtcod.KEY_F1:
        advanced_msgbox("INSTRUCTIONS", INSTRUCTIONS, width=60, color=libtcod.dark_green)
 
    elif key.vk == libtcod.KEY_ESCAPE:
        return 'exit'  #exit game
 
    if game_state == 'playing':
        if player.wait > 0:  #don't take a turn yet if still waiting
            player.wait -= 1
            return
        #movement keys
        if key.vk == libtcod.KEY_UP or key.vk == libtcod.KEY_KP8:
            player_move_or_attack(0, -1)
        elif key.vk == libtcod.KEY_DOWN or key.vk == libtcod.KEY_KP2:
            player_move_or_attack(0, 1)
        elif key.vk == libtcod.KEY_LEFT or key.vk == libtcod.KEY_KP4:
            player_move_or_attack(-1, 0)
        elif key.vk == libtcod.KEY_RIGHT or key.vk == libtcod.KEY_KP6:
            player_move_or_attack(1, 0)
        elif key.vk == libtcod.KEY_HOME or key.vk == libtcod.KEY_KP7:
            player_move_or_attack(-1, -1)
        elif key.vk == libtcod.KEY_PAGEUP or key.vk == libtcod.KEY_KP9:
            player_move_or_attack(1, -1)
        elif key.vk == libtcod.KEY_END or key.vk == libtcod.KEY_KP1:
            player_move_or_attack(-1, 1)
        elif key.vk == libtcod.KEY_PAGEDOWN or key.vk == libtcod.KEY_KP3:
            player_move_or_attack(1, 1)
        elif key.vk == libtcod.KEY_KP5:
            pass  #do nothing ie wait for the monster to come to you
 
        else:
            #test for other keys
            key_char = chr(key.c)
 
            if key_char == 'g':
                #pick up an item
                for object in objects:  #look for an item in the player's tile
                    if object.x == player.x and object.y == player.y and object.item:
                        object.item.pick_up()
                        break
 
            # Ranged attack
            if key_char == 'r':
                ranged_weapon = get_primary_ranged_weapon()
                if(ranged_weapon != None):
                    player_ranged_attack(ranged_weapon)
 
            # Choose new ammo
            if key_char == 'a':
                choose_ammo()
 
            if key_char == 'c':
                #show character information
                level_up_xp = LEVEL_UP_BASE + player.level * LEVEL_UP_FACTOR
                msgbox('Character Information\n\nLevel: ' + str(player.level) + '\nExperience: ' + str(player.combatant.xp) +
                    '\nExperience to level up: ' + str(level_up_xp) + '\n\nMaximum HP: ' + str(player.combatant.max_hp) +
                    '\nAttack: ' + str(player.combatant.strength) + '\nDefense: ' + str(player.combatant.defense), CHARACTER_SCREEN_WIDTH)
 
            if key_char == 'd':
                #show the inventory; if an item is selected, drop it
                chosen_item = inventory_menu('Press the key next to an item to DROP it, or any other to cancel.\n')
                if chosen_item is not None:
                    chosen_item.drop()
            
            if key_char == 'i':
                #show the inventory; if an item is selected, use it
                chosen_item = inventory_menu('\nPress the key next to an item to USE it, or any other to cancel.\n')
                if chosen_item is not None:
                    chosen_item.use()
            
            if key_char == '>':
                #go down stairs, if the player is on them
                if downStairs.x == player.x and downStairs.y == player.y:
                    next_level()
 
            if key_char == '<':
                #go up stairs, if the player is on them
                if upStairs.x == player.x and upStairs.y == player.y:
                    previous_level()
 
            return 'didnt-take-turn'
 
 
def get_primary_ranged_weapon():
    for obj in inventory:
        if obj.equipment and obj.equipment.is_equipped and obj.equipment.slot == 'main hand':
                return obj
    return None
 
 
##
## GUI Functions
##
 
# Displays a menu with header and options
def menu(header, options, width, color=libtcod.lighter_green):
    if len(options) > 26: raise ValueError('Cannot have a menu with more than 26 options.')
    #calculate total height for the header (after auto-wrap) and one line per option
    header_height = libtcod.console_get_height_rect(con, 0, 0, width, SCREEN_HEIGHT, header)
    if header == '':
        header_height = 0
    height = len(options) + header_height + 1
 
    #create an off-screen console that represents the menu's window
    window = libtcod.console_new(width, height)
 
    #print the header, with auto-wrap
    libtcod.console_set_default_foreground(window, color)
    libtcod.console_set_default_background(window, libtcod.darkest_gray)
    libtcod.console_print_rect_ex(window, 0, 0, width, height, libtcod.BKGND_NONE, libtcod.LEFT, header)
 
    #print all the options
    y = header_height
    letter_index = ord('a')
    for option_text in options:
        text = '(' + chr(letter_index) + ') ' + option_text
        libtcod.console_print_ex(window, 0, y, libtcod.BKGND_NONE, libtcod.LEFT, text)
        y += 1
        letter_index += 1
 
    #blit the contents of "window" to the root console
    x = SCREEN_WIDTH/2 - width/2
    y = SCREEN_HEIGHT/2 - height/2
    text_alpha = 1.0
    back_alpha = 0.85
    libtcod.console_blit(window, 0, 0, width, height, 0, x, y, text_alpha, back_alpha)
 
    #present the root console to the player and wait for a key-press
    libtcod.console_flush()
    key = libtcod.console_wait_for_keypress(True)
    
    if key.vk == libtcod.KEY_ENTER and key.lalt:
        #Alt+Enter: toggle fullscreen
        libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
    
    #convert the ASCII code to an index; if it corresponds to an option, return it
    index = key.c - ord('a')
    if index >= 0 and index < len(options): return index
    return None
 
 
# Display a message box with multiple lines of text
def advanced_msgbox(header, lines, width=50, color=libtcod.white):
    header_height = libtcod.console_get_height_rect(con, 0, 0, width, SCREEN_HEIGHT, header)
    if header == '':
        header_height = 0
    height = 2*len(lines) + header_height + 1
 
    #create an off-screen console that represents the menu's window
    window = libtcod.console_new(width, height)
 
    #print the header, with auto-wrap
    libtcod.console_set_default_foreground(window, color)
    libtcod.console_set_default_background(window, libtcod.darkest_gray)
    libtcod.console_print_rect_ex(window, 0, 0, width, height, libtcod.BKGND_NONE, libtcod.LEFT, header)
 
    #print all the lines
    y = header_height + 2
    for line in lines:
        libtcod.console_print_ex(window, 0, y, libtcod.BKGND_NONE, libtcod.LEFT, line)
        y += 2
 
    #blit the contents of "window" to the root console
    x = SCREEN_WIDTH/2 - width/2
    y = SCREEN_HEIGHT/2 - height/2
    text_alpha = 1.0
    back_alpha = 0.85
    libtcod.console_blit(window, 0, 0, width, height, 0, x, y, text_alpha, back_alpha)
 
    #present the root console to the player and wait for a key-press
    libtcod.console_flush()
    key = libtcod.console_wait_for_keypress(True)
    
    if key.vk == libtcod.KEY_ENTER or key.vk == libtcod.KEY_ESCAPE:
        return None
 
 
# Hack that uses menu() as a sort of "message box"
def msgbox(text, width=50, color=libtcod.sky):
    menu(text, [], width, color)
 
 
# Menu used as inventory
def inventory_menu(header):
    #show a menu with each item of the inventory as an option
    if len(inventory) == 0:
        header += '\n(Inventory is empty)\n'
        options = []
    else:
        options = []
        for item in inventory:
            isEquipped = item.equipment and item.equipment.is_equipped
            text = item.name
            #show additional information, in case it's equipped
            if isEquipped:
                text = '[' + item.equipment.slot + ']  ' + text
                if item.item and item.item.quantity > 1: # A little clarity, only 1 is equipped
                    text = text + '  x (1 equipped /' + str(item.item.quantity) + ' total)'
            if item.item and item.item.quantity > 1 and not isEquipped:
                text = text + '  x ' + str(item.item.quantity)
            options.append(text)
 
    index = menu(header, options, INVENTORY_WIDTH, color=libtcod.light_green)
 
    #if an item was chosen, return it
    if index is None or len(inventory) == 0: return None
    return inventory[index].item
 
 
def ammo_menu():
	# Show a menu with each item of the ammunition as an option
	header = "Select Ammunition"
	ammo_keys = []
	if len(player.ammo) == 0:
		header += '\n(No ammunition)\n'
		options = []
	else:
		options = []
		for name in player.ammo.keys():
			text = name + '  x' + str(player.ammo[name].quantity)
			options.append(text)
			ammo_keys.append(name)
	index = menu(header, options, INVENTORY_WIDTH, color=libtcod.light_green)
	# If an item was chosen, return it
	if index is None or len(player.ammo.keys()) == 0 : return None
	return player.ammo[ammo_keys[index]]
 
# Render a bar (used for HP, XP, etc)
def render_bar(x, y, total_width, name, value, maximum, bar_color, back_color, value_color = libtcod.white):
    #first calculate the width of the bar
    bar_width = int(float(value) / maximum * total_width)
 
    #render the background first
    libtcod.console_set_default_background(panel, back_color)
    libtcod.console_rect(panel, x, y, total_width, 1, False, libtcod.BKGND_SCREEN)
 
    #now render the bar on top
    libtcod.console_set_default_background(panel, bar_color)
    if bar_width > 0:
        libtcod.console_rect(panel, x, y, bar_width, 1, False, libtcod.BKGND_SCREEN)
 
    #finally, some centered text with the values
    libtcod.console_set_default_foreground(panel, value_color)
    libtcod.console_print_ex(panel, x + total_width / 2, y, libtcod.BKGND_NONE, libtcod.CENTER,
        name + ': ' + str(value) + '/' + str(maximum))
 
 
# Display a message in the console
def message(new_msg, color = libtcod.white):
    #split the message if necessary, among multiple lines
    new_msg_lines = textwrap.wrap(new_msg, MSG_WIDTH)
 
    for line in new_msg_lines:
        #if the buffer is full, remove the first line to make room for the new one
        if len(game_msgs) == MSG_HEIGHT - 1:
            del game_msgs[0]
 
        #add the new line as a tuple, with the text and the color
        game_msgs.append( (line, color) )
 
##
## End of GUI functions
##
 
 
# Displays the main menu
def main_menu():
    img = libtcod.image_load('menu_bk.jpg')
 
    while not libtcod.console_is_window_closed():
        #show the background image, at twice the regular console resolution
        libtcod.image_blit_2x(img, 0, 0, 0)
 
        #show the game's title, and some credits!
        libtcod.console_set_default_foreground(0, libtcod.dark_green)
        libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT/2-4, libtcod.BKGND_NONE, libtcod.CENTER,
            'ARROGUELLA')
        libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT-2, libtcod.BKGND_NONE, libtcod.CENTER,
            'By Brian & Aiden Shef')
 
        #show options and wait for the player's choice
        choice = menu('', ['Play a new game', 'Continue last game', 'Instructions', 'Quit'], 24, color=libtcod.dark_green)
 
        if choice == 0:  #new game
            new_game()
            play_game()
        if choice == 1:  #load last game
            try:
                load_game()
            except:
                msgbox('\n No saved game to load.\n', 24)
                continue
            play_game()
        if choice == 2: # Instructions
            advanced_msgbox("INSTRUCTIONS", INSTRUCTIONS, width=60, color=libtcod.dark_green)
        elif choice == 3:  #quit
            break
 
 
 
 
#############################################
# Primary logic
#############################################
 
# Open a new empty shelve (possibly overwriting an old one) to write the game data
def save_game():
    file = shelve.open('savegame', 'n')
    file['map'] = map
    file['objects'] = objects
    file['player_index'] = objects.index(player)  #index of player in objects list
    file['inventory'] = inventory
    file['game_msgs'] = game_msgs
    file['game_state'] = game_state
    file['stairs_index'] = objects.index(downStairs)
    file['upstairs_index'] = objects.index(upStairs)
    file['dungeon_level'] = dungeon_level
    file.close()
 
 
# Open the previously saved shelve and load the game data
def load_game():
    global map, objects, player, inventory, game_msgs, game_state, downStairs, upStairs, dungeon_level
 
    file = shelve.open('savegame', 'r')
    map = file['map']
    objects = file['objects']
    player = objects[file['player_index']]  #get index of player in objects list and access it
    inventory = file['inventory']
    game_msgs = file['game_msgs']
    game_state = file['game_state']
    downStairs = objects[file['stairs_index']]
    upStairs = objects[file['upstairs_index']]
    dungeon_level = file['dungeon_level']
    file.close()
 
    initialize_fov()
 
 
# Starts a new game
def new_game():
	global player, inventory, game_msgs, game_state, dungeon_level
	
	#create object representing the player
	skills = Skill()
	combat_component = Combatant(hp=PLAYER_START_HP, defense=PLAYER_START_DEFENSE, strength=PLAYER_START_STRENGTH, dexterity=PLAYER_START_DEXTERITY, intelligence=PLAYER_START_INTELLIGENCE, mana=PLAYER_START_MANA, mana_refresh_rate=PLAYER_START_MANA_REFRESH_RATE, hp_refresh_rate=PLAYER_TOWN_HP_REFRESH_RATE, skill_component=skills, xp=0, death_function=player_death)
	player = Object(0, 0, '@', 'player', libtcod.light_sky, blocks=True, speed=PLAYER_SPEED, combatant=combat_component)
	player.level = 0
	player.money = 0.00
	player.ammo = {}
	player.current_ammo = None
	
	#generate map (at this point it's not drawn to the screen)
	dungeon_level = 0
	make_town_map() # Default, "from up"
	initialize_fov()
	game_state = 'playing'
	inventory = []
	game_msgs = []
	player.combatant.hp = player.combatant.max_hp
	player.combatant.mana = player.combatant.max_mana
	player.combatant.xp += 100
	message("Welcome to town, brave adventurer! It seems you've found...", libtcod.dark_green)
	message("...the entrance to the DUNGEONS OF ARROGUELLA!!", libtcod.dark_green)
 
 
# Advances to the next level of a dungeon
def next_level():
    global dungeon_level
    message('You take a moment to recover your strength.', libtcod.sky)
    player.combatant.heal(player.combatant.max_hp / 4)  #heal the player by 25% 
    message('You descend deeper into the the dungeon...', libtcod.sky)
    dungeon_level += 1
    make_map(from_down=False, from_up=True)  #create a fresh new level!
    initialize_fov()
 
 
# Return to the previous level of a dungeon
def previous_level():
    global dungeon_level
 
    dungeon_level -= 1
    if(dungeon_level == 0):
        message('You take a moment to recover your strength.', libtcod.sky)
        player.combatant.heal(player.combatant.max_hp / 2)  #heal the player by 50%
        message('You escape the dungeon...', libtcod.sky)
        message('...and make it back to town alive! (Game Saved)', libtcod.sky)
        save_game() # Save every time we make it back to town alive
        make_town_map()
    else:
        message('You take a moment to rest, and recover your strength.', libtcod.sky)
        player.combatant.heal(player.combatant.max_hp / 4)  #heal the player by 25%
        message('You ascend towards a way out of the dungeon...', libtcod.sky)
        make_map(from_down=True, from_up=False)  #create a fresh new level!
    initialize_fov()
 
 
# Initialize the FOV map, according to the generated map
def initialize_fov():
	global fov_recompute, fov_map
	fov_recompute = True
	
	libtcod.console_clear(con)  #unexplored areas start black (which is the default background color)
	
	#create the FOV map, according to the generated map
	fov_map = libtcod.map_new(MAP_WIDTH, MAP_HEIGHT)
	for y in range(MAP_HEIGHT):
		for x in range(MAP_WIDTH):
			libtcod.map_set_properties(fov_map, x, y, not map[x][y].block_sight, not map[x][y].blocked)
 
 
# Main gameplay method
def play_game():
	global key, mouse
	
	player_action = None
	
	mouse = libtcod.Mouse()
	key = libtcod.Key()
	
	# MAIN LOOP --------------------------------
	while not libtcod.console_is_window_closed():
		libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS|libtcod.EVENT_MOUSE,key,mouse)
	 
		#render the screen
		render_all() 
		libtcod.console_flush()
		
		# Check for levelling up
		check_level_up()
	 
		# Check for stats that need refreshing
		refresh_applicable_player_stats()
	 
		#erase all objects at their old locations, before they move
		for object in objects:
			object.clear()
	 
		#handle keys and exit game if needed
		player_action = handle_keys()
		if player_action == 'exit':
			save_game()
			break
	 
		#let monsters take their turn
		if game_state == 'playing':
			for object in objects:
				if object.ai:
					if object.wait > 0:  #don't take a turn yet if still waiting
						object.wait -= 1
					else:
						object.ai.take_turn()
	
 
 
#############################################
# Initialization & Main
#############################################
 
libtcod.console_set_custom_font('arial12x12.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)
libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'Arroguella', False)
libtcod.sys_set_fps(LIMIT_FPS)
 
con = libtcod.console_new(MAP_WIDTH, MAP_HEIGHT)
panel = libtcod.console_new(CHARACTER_PANEL_WIDTH, CHARACTER_PANEL_HEIGHT)
look_panel = libtcod.console_new(LOOK_PANEL_WIDTH, LOOK_PANEL_HEIGHT)
msg_panel = libtcod.console_new(MSG_WIDTH, MSG_HEIGHT)

main_menu()
 

